<?php
namespace app\common\model;
use think\Model;

/**
 * 需求模块
 */
class Coupon extends Model {
	protected $insert = ['add_time'];

    protected function setAddTimeAttr(){
        return time();
    }

    protected static function init(){
        self::beforeInsert(function($data){
            $data['start_use'] = strtotime($data['start_use']);
            $data['end_use'] = strtotime($data['end_use']);
            $data['issue_time'] = strtotime($data['issue_time']);
            $data['validate_time'] = $data['issue_time'] + 30 * 24 *3600;
        });
    }

    //地图显示优惠券
    public function couponByMap($where = [],$lng = '',$lat = '',$having = ''){
            $list =  $this->alias('r')->join(['bz_user' => 'u'],'u.id = r.user_id')->join(['bz_user_position'=>'p'],'p.user_id = r.user_id')
                    ->where('get_num','gt',0)->where('issue_time','elt',time())->where('validate_time','egt',time())->where($where)
                    ->field("r.id,p.lng,p.lat,z_num,i_num,get_num,jump,foreign_key,u.photo_path,u.nick_name,ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(( $lat * PI() / 180 - lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(lat * PI() / 180) * POW(SIN(($lng * PI() / 180 - lng * PI() / 180) / 2),2)))) AS juli")
                    ->having($having)
                    ->select();

            return empty($list)?[]:$list;

    }
}
